package Server.Add;

import bean.userBean;
import dao.userDao;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class userServer {
    public String insert (HttpServletRequest request) {

        String userNumber = "0";
        String msg = "";

        try {
            String username, password, password2;

            username  	= request.getParameter("username"); 		//获取输入的值
            password  	= request.getParameter("password");
            password2  	= request.getParameter("password2");

            if (username == null || password == null || password2 == null) {
                msg = "输入不正确！";								//值为null的原因：输入框名称不对，或者在地址栏直接输入本页网址
                return userNumber;
            }
            username = username.trim();

            if (username.length() < 1 || username.length() > 45) {
                msg = "用户名为1~45个字符！";
                return userNumber;
            }

            if (password.length() < 1 || password.length() > 45) {
                msg = "密码为1~45个字符！";
                return userNumber;
            }
            if (password2.length() < 1 || password2.length() > 45) {
                msg = "“密码确认”为1~45个字符！";
                return userNumber;
            }
            if (password.equals(password2) == false) {
                msg = "请确认2个密码保持一致！";
                return userNumber;
            }


            userBean user = new userBean();

            //user.setUserId(userNumber);
            user.setUserName(username);
            user.setPassword(password);
            user.setUserType("user");
            userDao userDao = new userDao();
            userNumber = userDao.insert(request, user);				//****新添记录

            if (userNumber.equals("0")) {
                msg += "新添记录失败！请重试。";
                return userNumber;
            }

            msg += "新添记录成功。";
            request.getSession().setAttribute("msg", msg);		//通过session传递消息。消息将显示在详情页中
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            return userNumber;										//返回新添记录的ID

        } catch (Exception e) {
            msg += "系统发生错误。";
            e.printStackTrace();
        } finally {
            if (request.getAttribute("msg") != null) {
                msg += request.getAttribute("msg").toString();
            }
            request.setAttribute("msg", msg);
        }

        return userNumber;
    }
}
